/*
 * Copyright (C) 2009, 2010, B3log Team
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.b3log.nide.service.maven.cmd;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.b3log.latke.service.ServiceException;
import org.b3log.nide.service.maven.MavenManager;

/**
 * Abstract Maven command.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.5, Nov 29, 2010
 */
public abstract class AbstractMvnCommand extends Observable implements Command {

    /**
     * Logger.
     */
    private static final Logger LOGGER =
            Logger.getLogger(AbstractMvnCommand.class.getName());

    /**
     * Runs a Maven command with the specified parameters in the specified
     * working directory.
     *
     * @param dir the path of specified working directory
     * @param params the specified parameters
     * @param outputListeners the specified output listeners
     * @throws ServiceException service exception
     */
    protected final void mvn(final String dir, final String params,
                             final Observer... outputListeners)
            throws ServiceException {
        try {
            final String cmd = MavenManager.getMvnPath() + params;
            LOGGER.log(Level.INFO,
                            "Executing command[{0}] in directory[{1}]",
                            new Object[]{cmd, dir});
            final Process cmdProcess = Runtime.getRuntime().exec(
                    cmd, null, new File(dir));

            processProcessExecFeedback(cmdProcess, outputListeners);
        } catch (final IOException e) {
            LOGGER.log(Level.SEVERE, e.getMessage(), e);
            throw new ServiceException(e);
        }
    }

    /**
     * Gets the specified process execution feedback output.
     *
     * @param process the specified process
     * @param outputListeners the specified output listeners
     * @throws IOException io exception
     */
    private void processProcessExecFeedback(final Process process,
                                            final Observer... outputListeners)
            throws IOException {
        final InputStream inputStream = process.getInputStream();

        final BufferedReader bufferedReader =
                new BufferedReader(new InputStreamReader(inputStream));

        final CommandFeedback commandFeedback = new CommandFeedback();
        for (final Observer outputListener : outputListeners) {
            if (null == outputListener) {
                LOGGER.warning("No command output listener");
            } else {
                commandFeedback.addObserver(outputListener);
            }
        }

        String line = bufferedReader.readLine();

        try {
            while (null != line) {
                line = line.replaceFirst("\\[[A-Z]+\\]", "");
                commandFeedback.append(line + "\r\n");
                LOGGER.fine(line);

                line = bufferedReader.readLine();
            }
        } finally {
            bufferedReader.close();
        }
    }
}
